const util = require('../../utils/util.js');
const api = require('../../config/api.js');
//获取应用实例
const app = getApp();

Page({

    data: {
        showStrategyPop: false,
        showDatePop: false,
        showRemarkPop: false,

        strategyId: 1,
        activeNames: [1],

        defaultStrategyName: "",
        defaultStrategyDesc: "",
        optype: '',
        recordId: '',
        minDate: "",
        calendarMaxDate: new Date().getTime(),

        defaultDate: "",
        strategyList: [],
        stockList: [],
        zhishu: [],

        k: false,
        choosenDateTimeStamp: new Date(new Date().toLocaleDateString()).getTime(),

        noticeContent: "",
 
        itemTitle: "策略选择",
        multiStrategyIds: [],
        strategySwitchList: [],
        selectSingle: true,
        strategyLoading:true,
        showNoticeBar:true
    },
    onChangeSelectMode() {
        this.setData({
            strategySwitchList: this.data.strategySwitchList.map(x => false),
            selectSingle: !this.data.selectSingle
        })
    },
    onChange(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    onCloseNoticeBar(){
        this.setData({
            showNoticeBar:false
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onLoad: function () {
        // 每日登陆加积分
        util.request(api.DailyFirstLogin).then(resp => {
            if (resp.success && resp.data.firstLogin) {
                wx.showToast({
                    title: '每日登陆.积分 +' + resp.data.rewardPoint,
                    icon: "none"
                })
            }
        })
        app.globalData.k = false

        // 配置数据
        util.request(api.IndexData).then(resp => {
            if (resp.success) {
                app.globalData.k = resp.data.k
                wx.setStorageSync('k', resp.data.k);
                this.setData({
                    noticeContent: resp.data.noticeContent,
                    k: resp.data.k
                })
            }
        })


        // 获取策略列表
        util.request(api.StrategyList).then(res => {
            if (res.success) {
                if (res.data.length > 0) {
                    // 收藏的 strategyList 放入本地缓存中
                    let collectStrategy = res.data.map(x => {
                        return {
                            id: x.id,
                            text: x.strategyName,
                            desc: x.strategyDescription,
                        }
                    })
                    this.getTabBar().setCartNumber(wx.getStorageSync('collectStrategy').length)
                    wx.setStorageSync('collectStrategy', res.data.map(x => {
                        return {
                            id: x.id,
                            text: x.strategyName
                        }
                    }))
                    let swithcList = collectStrategy.map(x => false)
                    swithcList[0] = true
                    this.setData({
                        strategyList: collectStrategy,
                        strategySwitchList: swithcList,
                        defaultStrategyName: res.data[0].strategyName,
                        defaultStrategyDesc: res.data[0].strategyDescription,
                        defaultDate: util.formatDate(new Date(this.data.choosenDateTimeStamp)),
                        strategyId: res.data[0].id
                    })
                } else {
                    this.getTabBar().setCartNumber(0)
                    wx.setStorageSync('collectStrategy', [])
                    this.setData({
                        strategyList: [],
                        defaultStrategyName: '',
                        defaultStrategyDesc: '',
                        defaultDate: util.formatDate(new Date(this.data.choosenDateTimeStamp)),
                        strategyId: 0
                    })
                }

            }
        }).then(res => {
            // 从服务器获取最大的推荐日期 时间戳
            util.request(api.MaxRecommendTime).then(resp => {
                if (resp.success) {
                    this.setData({
                        choosenDateTimeStamp: resp.data,
                        defaultDate: util.formatDate(new Date(resp.data)),
                        calendarMaxDate:new Date(resp.data).getTime()
                    })

                    // 设置选股结果
                    this.setDailyStockRecommends({
                        "strategyId": this.data.strategyId,
                        "dateTimestamp": resp.data
                    })
                }
            })
        })
    },
    onConfirmStrategy() {
        this.setData({
            showStrategyPop:false,
            strategyLoading:true
        })
        let strategySwitchList = this.data.strategySwitchList
        let strategyList = this.data.strategyList
        let requestParam = ''
        for (let idx = 0; idx < strategySwitchList.length; idx++) {
            if (strategySwitchList[idx]) {
                requestParam = requestParam + strategyList[idx].id + ','
            }
        }
       
        let choosenDateTimeStamp = this.data.choosenDateTimeStamp
        this.setDailyStockRecommends({
            "strategyId": requestParam,
            "dateTimestamp": choosenDateTimeStamp
        })
    },
    onClearStrategy() {
        this.setData({
            strategySwitchList: this.data.strategySwitchList.map(x => false)
        })
    },
    multiSelectStrategy(event) {
        let swichtList = this.data.strategySwitchList
        if (this.data.selectSingle) {
            swichtList = swichtList.map(x => false)
        }
        swichtList[event.target.dataset.index] = event.detail

        this.setData({
            strategySwitchList: swichtList
        })

    },
    onShow: function () {
        this.getTabBar().init();
        let collectStrategyCache = wx.getStorageSync('collectStrategy')
        if (!collectStrategyCache) {
            collectStrategyCache = []
        }
        this.getTabBar().setCartNumber(collectStrategyCache.length)

        let currentCollectStrategy = this.data.strategyList.map(x => {
            return {
                id: x.id,
                text: x.text
            }
        })
        let isSame = true
        let collec = collectStrategyCache.map(x => x.id)
        if (currentCollectStrategy.length != collectStrategyCache.length) {
            isSame = false
        } else {
            for (let it = 0; it < currentCollectStrategy.length; it++) {
                if (collec.indexOf(currentCollectStrategy[it].id) == -1) {
                    isSame = false
                    break
                }
            }
        }

        console.log('是否一样:', isSame)
        if (!isSame) {
            this.setData({
                strategyLoading:true
            })
            // 不一样 需要重新赋值. 可以重复选股初始化的逻辑, 只是把策略列表的数据进行更换
            if (collectStrategyCache.length > 0) {
                util.request(api.StrategyList).then(res => {
                    if (res.success) {
                        if (res.data.length > 0) {
                            // 收藏的 strategyList 放入本地缓存中
                            let collectStrategy = res.data.map(x => {
                                return {
                                    id: x.id,
                                    text: x.strategyName,
                                    desc: x.strategyDescription,
                                }
                            })
                            this.getTabBar().setCartNumber(wx.getStorageSync('collectStrategy').length)
                            wx.setStorageSync('collectStrategy', res.data.map(x => {
                                return {
                                    id: x.id,
                                    text: x.strategyName
                                }
                            }))
                            let swithcList = collectStrategy.map(x => false)
                            swithcList[0] = true
                            this.setData({
                                strategyList: collectStrategy,
                                strategySwitchList: swithcList,
                                defaultStrategyName: res.data[0].strategyName,
                                defaultStrategyDesc: res.data[0].strategyDescription,
                                defaultDate: util.formatDate(new Date(this.data.choosenDateTimeStamp)),
                                strategyId: res.data[0].id
                            })
                        } else {
                            this.getTabBar().setCartNumber(0)
                            wx.setStorageSync('collectStrategy', [])
                            this.setData({
                                strategyList: [],
                                defaultStrategyName: '',
                                defaultStrategyDesc: '',
                                defaultDate: util.formatDate(new Date(this.data.choosenDateTimeStamp)),
                                strategyId: 0
                            })
                        }

                    }
                }).then(res => {
                    // 设置选股结果
                    this.setDailyStockRecommends({
                        "strategyId": this.data.strategyId,
                        "dateTimestamp": this.data.choosenDateTimeStamp
                    })
                })

            } else {
                // 缓存为空的情况下 需要重新获取
                this.init()
            }



        }

    },
    init() {
        util.request(api.StrategyList).then(res => {
            if (res.success) {
                if (res.data.length > 0) {
                    // 收藏的 strategyList 放入本地缓存中
                    let collectStrategy = res.data.map(x => {
                        return {
                            id: x.id,
                            text: x.strategyName,
                            desc: x.strategyDescription,
                        }
                    })
                    this.getTabBar().setCartNumber(wx.getStorageSync('collectStrategy').length)
                    wx.setStorageSync('collectStrategy', res.data.map(x => {
                        return {
                            id: x.id,
                            text: x.strategyName
                        }
                    }))
                    let swicthList = collectStrategy.map(x => false)
                    swicthList[0] = false

                    this.setData({
                        strategyList: collectStrategy,
                        strategySwitchList: swichList,
                        defaultStrategyName: res.data[0].strategyName,
                        defaultStrategyDesc: res.data[0].strategyDescription,
                        defaultDate: util.formatDate(new Date(this.data.choosenDateTimeStamp)),
                        strategyId: res.data[0].id
                    })
                }

            } else {
                this.getTabBar().setCartNumber(0)
                wx.setStorageSync('collectStrategy', [])
                this.setData({
                    strategyList: [],
                    defaultStrategyName: '',
                    defaultStrategyDesc: '',
                    defaultDate: util.formatDate(new Date(this.data.choosenDateTimeStamp)),
                    strategyId: 0
                })
            }

        }).then(res => {
            // 从服务器获取最大的推荐日期 时间戳
            util.request(api.MaxRecommendTime).then(resp => {
                if (resp.success) {
                    this.setData({
                        choosenDateTimeStamp: resp.data,
                        defaultDate: util.formatDate(new Date(resp.data)),
                        calendarMaxDate:new Date(resp.data).getTime()
                    })

                    // 设置选股结果
                    this.setDailyStockRecommends({
                        "strategyId": this.data.strategyId,
                        "dateTimestamp": resp.data
                    })
                }
            })
        })
    },
    onChooseDate(event) {
        this.setDailyStockRecommends({
            "strategyId": this.data.strategyId,
            "dateTimestamp": new Date(event.detail).getTime()
        })
        this.setData({
            showDatePop: false,
            choosenDateTimeStamp: new Date(event.detail).getTime(),
            defaultDate: util.formatDate(new Date(event.detail))
        })
    },


    setDailyStockRecommends(param) {
        util.request(api.StockRecommendListV2, param).then(resp => {
            if (!resp.success) {
                wx.showToast({
                    title: resp.message,
                    icon: 'none'
                })
                return
            }
            let tempArr = resp.data.stockStrategyRecommend.map(item => {
                item.dataUrl = item.dailyRaiseAndFallImgUrl
                item.imgType = 'daily'
                return item
            })
            this.setData({
                stockList: tempArr,
                defaultStrategyDesc: resp.data.stockStrategyDesc,
                strategyLoading:false
            })
        })
    },

    getZhishu() {
        util.request(api.Zhishu).then(resp => {
            if (resp.success) {
                this.setData({
                    zhishu: resp.data
                })
            }
        })
    },

    getMaxRecommedTimestamp() {
        util.request(api.MaxRecommendTime).then(resp => {
            if (resp.success) {

                this.setData({
                    choosenDateTimeStamp: resp.data
                })
            }
        })
    },
    collectStock(e) {

        let {
            index,
            stockcode
        } = e.target.dataset
        let stockList = this.data.stockList
        for (let idx = 0, len = stockList.length; idx < len; idx++) {
            if (stockcode == stockList[idx].stockCode) {
                index = idx
                break
            }
        }

        let tempJson = stockList[index]
        let _this = this
        util.request(!tempJson.collected ? api.CollectStock : api.CancleCollectStock, {
            "stockCode": tempJson.stockCode
        }).then(resp => {
            if (resp.success) {
                tempJson.collected = !tempJson.collected
                _this.setData({
                    stockList
                }, () => {
                    wx.showToast({
                        title: tempJson.collected ? '收藏成功-' + resp.data.decrPoints + '积分' : '取消成功',
                        icon: 'none'
                    })

                    if (tempJson.collected) {
                        _this.setData({
                            showRemarkPop: false,
                            optype: 'add',
                            recordId: resp.data.recordId
                        })
                    }
                })
            } else {
                wx.showToast({
                    title: resp.message,
                    icon: 'none'
                })
            }
        })
    },
    showStrategyPicker() {
        this.setData({
            showStrategyPop: !this.data.showStrategyPop
        });
    },
    showDatePicker() {
        this.setData({
            showDatePop: true
        })
    },
    onClose() {

        this.setData({
            showStrategyPop: false,
            showDatePop: false
        });
    },

    /**抽屉默认展示事件 */
    onChooseStrategy(event) {
        const {
            picker,
            value,
            index
        } = event.detail;
        let strategyList = this.data.strategyList
        util.request(api.StockRecommendList, {
            "strategyId": value.id,
            "dateTimestamp": this.data.choosenDateTimeStamp
        }).then(resp => {
            let tempArr = []
            if (!resp.success) {
                wx.showToast({
                    title: resp.message,
                    icon: 'none'
                })
            } else {
                tempArr = resp.data.map(item => {
                    item.dataUrl = item.dailyRaiseAndFallImgUrl
                    item.imgType = 'daily'
                    return item
                })
            }

            this.setData({
                stockList: tempArr,
                showStrategyPop: false,
                strategyId: value.id,
                defaultStrategyName: value.text,
                defaultStrategyDesc: strategyList[index].desc,
            })
            if (!resp.success) {
                wx.showToast({
                    title: resp.message,
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },

    /**
     * 切换图片
     */
    toggleImg(event) {
        let {
            index,
            type,
            stockcode
        } = event.target.dataset
        let {
            stockList
        } = this.data

        for (let idx = 0, len = stockList.length; idx < len; idx++) {
            if (stockcode == stockList[idx].stockCode) {
                index = idx
                break
            }
        }
        let tempJson = stockList[index]
        let isSH = tempJson.stockCode.substr(0, 2) == '60' || tempJson.stockCode.substr(0, 2) == '68'
        let tempUrl = `http://image.sinajs.cn/newchart/${type}/n/${isSH ? 'sh' : 'sz'}${tempJson.stockCode}.gif`
        tempJson.dataUrl = tempUrl
        tempJson.imgType = type
        this.setData({
            stockList
        })
    },

    /**预览图片 */
    prviewImg(event) {
        let {
            dataurl,
        } = event.target.dataset
        wx.previewImage({
            urls: [dataurl],
            current: 'current',
            showmenu: true
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
})